package com.ruoyi.listener;

import com.rabbitmq.client.Channel;
import com.ruoyi.platform.constant.MqConstants;
import com.ruoyi.platform.system.domain.SysOperLog;
import com.ruoyi.platform.system.service.ISysOperLogService;
import com.ruoyi.platform.utils.ip.AddressUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 *  Mq监听者
 */
@Component
@Slf4j
public class MqListener {

    @Autowired
    private ISysOperLogService sysOperLogService;

    /**
     * 日志队列监听者
     * @param
     * @param channel
     * @param message
     */
    @RabbitListener(queues = MqConstants.LOG_QUEUE_NAME)
    public void logListener(SysOperLog operLog, Channel channel, Message message) {
        try {
            log.debug("日志队列监听者接收到的消息：{}",operLog);
            // 远程查询操作地点
            operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
            sysOperLogService.insertOperlog(operLog);
            channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
        } catch (Exception e) {
            log.error("日志队列消费消息异常",e);
            try {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        }
    }

}
